package com.example.demo.controller;

import com.example.demo.config.MqttBroker;
import com.example.demo.entity.ProductInfo;
import com.example.demo.entity.UserProductinfo;
import com.example.demo.service.UserProductinfoService;
import com.example.demo.util.GetMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/register")
@RequiredArgsConstructor
@Component
public class RegisterController {
    private final UserProductinfoService userProductinfoService;
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @PostMapping("/register")
    public GetMessage getRegister (String userId, @RequestBody UserProductinfo userProductinfo) throws JsonProcessingException, MqttException {
        String code="";
        String appId=userProductinfo.getAppid();
        String trainingId=userProductinfo.getTrainingid();
        //String userId=token;
        code=Util.getCode(appId);

        Map<String,Object> map=new HashMap<>();
        map.put("type","register");
        map.put("appId",appId);
        map.put("trainingId",trainingId);
        map.put("data",code);
        List<UserProductinfo> u=userProductinfoService.selectProductInfo(userId,appId,trainingId);
        if(u.size()==0){
            userProductinfo.setUserid(userId);
            userProductinfo.setCategorycode(code);
            userProductinfoService.save(userProductinfo);
        }else {
            for(int i=0;i<u.size();i++){
                if(u.get(i).getProductmodel().equals(userProductinfo.getProductmodel())){
                    return new GetMessage("已注册该型号","500",code);
                }
                if(i==u.size()-1){
                    userProductinfo.setUserid(userId);
                    userProductinfo.setCategorycode(code);
                    userProductinfoService.save(userProductinfo);
                }
            }
        }

        String payload = objectMapper.writeValueAsString(map);
        MqttBroker.mqttClient.publish("StepInfo/supply/"+userId,new MqttMessage(payload.getBytes(StandardCharsets.UTF_8)));
        return new GetMessage("成功","200",code);
    }


}
